# coding=utf-8
import configparser
import logging
import os
import time
from multiprocessing import Process
from queue import Queue

import redis

from GetRtspData import GetRtspData

def get_logger(camera_id, rtsp_type):
    # 第一步，创建一个logger
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)  # Log等级总开关
    # 第二步，创建一个handler，用于写入日志文件
    rq = str(time.strftime('%Y%m%d', time.localtime(time.time()))) + '_' + str(camera_id) + '_' + str(rtsp_type)
    log_path = 'logs/2/'
    # log_path = '/opt/python' + '/logs/'
    # print('log_path', log_path)
    if not os.path.exists(log_path):
        os.mkdir(log_path)

    log_name = log_path + rq + '.log'
    logfile = log_name
    fh = logging.FileHandler(logfile)
    fh.setLevel(logging.DEBUG)  # 输出到file的log等级的开关
    # 第三步，定义handler的输出格式
    formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
    fh.setFormatter(formatter)
    # 第四步，将logger添加到handler里面
    logger.addHandler(fh)
    return logger


def get_video_data(url, camera_id, retained_time):
    #读取redis配置文件
    cf = configparser.ConfigParser()
    cf.read('./conf/application_1.ini')
    redisHost = cf.get("redis", 'host')
    redisDb = cf.get("redis", "db")
    redisPort = cf.get("redis", "port")
    redisPassword = cf.get("redis", "password")
    iFrameFlag = cf.get("rtsp","iFrameFlag")
    if not all([redisHost, redisDb, redisPort, iFrameFlag]):
        logger.error('参数配置不能为空')
    if not redisPassword:
        pool = redis.ConnectionPool(host=redisHost, port=redisPort, password=redisPassword, db=redisDb, decode_responses=False)
    else:
        pool = redis.ConnectionPool(host=redisHost, port=redisPort, db=redisDb, decode_responses=False)
    # 主码流辅码流根据 rtsp_type 类型区分
    loggerRtspData = get_logger(camera_id, 0)
    with GetRtspData(str(url), pool, camera_id, retained_time, loggerRtspData, iFrameFlag) as sgg:
        print('start.....')
        sgg.StartPlay()


if __name__ == '__main__':

    logger = get_logger(1000, 1000)
    cameraDevs = []
    for s in open("conf/config_1.txt"):
        if s == "":
            continue
        str2 = s.split(',')
        # 将所有配置都放到相机配置集合中
        cameraDevs.append([str2[0], str2[1], int(str2[2])])
    logger.info('相机配置集合: ' + str(cameraDevs))

    cam_channel, video, q_camera_data, camera_code, camera_retained_time = {}, {}, {}, {}, {}
    for i in range(len(cameraDevs)):
        q_camera_data['q_camera{}_data'.format(i + 1)] = Queue()
        path = cameraDevs[i][0]
        code = cameraDevs[i][1]
        retain_time = cameraDevs[i][2]
        camera_code[path] = code
        camera_retained_time[path] = retain_time
        cam_channel['cam_channel{}'.format(i + 1)] = path
        #     print(path)
        video[path] = Process(target=get_video_data, args=(
            cam_channel.get('cam_channel{}'.format(i + 1)),
            cameraDevs[i][1], cameraDevs[i][2]
        ), name='camera{}_data'.format(i + 1))
    for i in range(len(cameraDevs)):
        video[cameraDevs[i][0]].start()
    while True:
        for k, v in video.items():
            proRtsp = video[k]
            # log = str(time.time()) + " " + k + ': ' + str(proRtsp.is_alive())
            # print(log)
            # logger.info(log)
            time.sleep(0.5)
            if not proRtsp.is_alive():
                time.sleep(1)
                # logger.info(str(camera_code[k]) + 'video offline need restart')
                video[k] = ""
                video[k] = Process(target=get_video_data, args=(k, camera_code[k], camera_retained_time[k]))
                video[k].start()
